import { route } from 'quasar/wrappers';
import { createMemoryHistory, createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import routes from './routes';

import { Message } from 'src/utils';
import { useUserStore } from 'src/stores';

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */
const whiteList = ['/login'];

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === 'history'
      ? createWebHistory
      : createWebHashHistory;

  const router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(process.env.VUE_ROUTER_BASE),
  });

  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    console.debug('before router:' + to.path);

    if (userStore.token) {
      if (to.path === '/login') {
        // 登录页面如果已登录直接跳转到首页
        next({ path: '/' });
      } else if (!userStore.username) {
        // 刚登录或刷新页面后需要获取用户信息
        try {
          await userStore.getUserInfo();
          next();
          // // 加载动态路由,同时保存删除动态路由的方法
          // accessRoutes.forEach((route) => {
          //   const r = router.addRoute(route);
          //   userStore.removeRoutes.push(r);
          // });
          // // 页面跳转
          // next({ ...to, replace: true });
          //LoadingBar.stop();
        } catch (err) {
          console.error('获取用户信息出错', err);
          Message.warning('获取用户信息出错，请重新登录。');
          await userStore.doLogout();
          next(`/login?redirect=${to.fullPath}`);
        }
      } else {
        next();
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.fullPath}`);
      }
    }
  });

  router.afterEach((to) => {
    console.debug('after router:' + to.path);
    document.title = to.meta.title ? to.meta.title + ' -- ' + process.env.APP_TITLE : '';
  });

  return router;
});
